import webapp2
import json
from google.appengine.ext import db
from images import Image

class Category(db.Model):
  name = db.StringProperty()
  image = db.ReferenceProperty(Image)

class CategoriesRequestHandler(webapp2.RequestHandler):
  def get(self):
    cats = Category.all().fetch(100)
    
    if self.request.params.has_key('html'):
      self.__showHtml(cats, self.response)
    else:
      self.__showJson(cats, self.response)

  def post(self):
    action = self.request.params['action']
    if action == 'add':
      name = self.request.params['name']
      image = self.__readUploadedFile(self.request, 'image')
      self.__addNewCategory(name, image)

    else:
      self.response.out.write("invalid action")

  def __readUploadedFile(self, request, paramName):
    data = ""
    buff = request.POST.get(paramName).file.read()
    while buff:
      data += buff
      buff = request.POST.get(paramName).file.read()
    return data

  def __addNewCategory(self, name, image):
    imageInDB = Image()
    imageInDB.data = image
    imageInDB.put()

    cat = Category()
    cat.name = name
    cat.image = imageInDB
    cat.put()

  def __showHtml(self, cats, response):
    response.headers['Content-Type'] = 'text/html'
    response.out.write('<html><head><title>Category list</title></head><body><table><tr>')
    for cat in cats:
      response.out.write('<td>' + cat.name + ':<img style="width:60px;height:60px" src="' + self.__getImageUrl(cat.image) + '"/></td>')
    response.out.write('</tr></body></html>')

  def __showJson(self, cats, response):
    response.headers['Content-Type'] = 'application/json'
    jsonCats = []
    for cat in cats:
      name = str(cat.name)
      url  = self.__getImageUrl(cat.image)
      jsonCats.append({
          'id': str(cat.key()),
          'name': str(cat.name),
          'url': self.__getImageUrl(cat.image),
        })

    response.out.write(json.dumps(jsonCats))
    
  def __getImageUrl(self, image):
    return "/imagesDB/%s" % str(image.key())

